/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VerReclamos.java
 *
 * Created on 08-jul-2012, 20:34:37
 */
package sistemadeproyectos;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author giancarlo
 */
public class VerReclamos extends javax.swing.JFrame {

    private ModeloReclamos reclamos;
    
    private String Asunto = "";
    
    private String Autor = "";
    
    private String FiltroTipo = "Todo";
    
    private String FiltroFecha = "Todo";
    
    ListSelectionModel rowSM;
    
    DefaultComboBoxModel<String> tipos_reclamos;
    
    DefaultComboBoxModel<String> tiempo_reclamos;
    
            
    /** Creates new form VerReclamos */
    public VerReclamos() throws SQLException {
        initComponents();
        this.reclamos = new ModeloReclamos();
        reclamos_table.setModel(reclamos);
        
        /*Activamos la opcion para poder seleccionar una fila*/
        reclamos_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        rowSM = reclamos_table.getSelectionModel();
        
        /*Inicializamos el Combo Box de filtros de tipos de reclamos*/
        tipos_reclamos = new DefaultComboBoxModel<String>();
        tipos_reclamos.addElement("Todo");
        tipos_reclamos.addElement("Remocion de Usuario");
        tipos_reclamos.addElement("Remocion de Archivo");
        filtro_tipos.setModel(tipos_reclamos);
        
        /*Inicializamos el Combo Box de fechas de realizacion de reclamos*/
        tiempo_reclamos = new DefaultComboBoxModel<String>();
        tiempo_reclamos.addElement("Todo");
        tiempo_reclamos.addElement("Hoy");
        filtro_tiempo.setModel(tiempo_reclamos);               
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        reclamos_table = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        filtro_tipos = new javax.swing.JComboBox();
        filtro_tiempo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sistemadeproyectos.SistemadeproyectosApp.class).getContext().getResourceMap(VerReclamos.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        reclamos_table.setName("reclamos_table"); // NOI18N
        jScrollPane1.setViewportView(reclamos_table);

        jButton1.setText(resourceMap.getString("Jreclamo_button.text")); // NOI18N
        jButton1.setName("Jreclamo_button"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), resourceMap.getString("jPanel1.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jPanel1.border.titleFont"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        filtro_tipos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        filtro_tipos.setName("filtro_tipos"); // NOI18N
        filtro_tipos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                filtro_tiposActionPerformed(evt);
            }
        });

        filtro_tiempo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        filtro_tiempo.setName("filtro_tiempo"); // NOI18N
        filtro_tiempo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                filtro_tiempoActionPerformed(evt);
            }
        });

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(filtro_tipos, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(filtro_tiempo, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(filtro_tipos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(filtro_tiempo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(88, 88, 88))
        );

        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(46, 46, 46)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(4, 4, 4)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (!rowSM.isSelectionEmpty()) {
            try {
                int selectedRow = rowSM.getMinSelectionIndex();

                /*El modelo que usamos para la tabla solo guarda valores String*/
                VerEntradaReclamo entrada = new VerEntradaReclamo(this, true, 
                        (String)reclamos.getValueAt(selectedRow, 4), //Asunto 
                        (String)reclamos.getValueAt(selectedRow, 0)); //Autor
                
                entrada.setVisible(true);
            }
            catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "Problema al conectar con la base de Datos: "
                    +e.getMessage(), "Error de Conexion", JOptionPane.ERROR_MESSAGE);
            }
        }
        else { 
            JOptionPane.showMessageDialog(this, "No ha selecionado ningun valor"
                ,"Seleccion Vacia", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void filtro_tiposActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filtro_tiposActionPerformed
        try {
            this.FiltroTipo = (String)(tipos_reclamos.getSelectedItem());
            reclamos.FiltrarReclamos(this.FiltroTipo, this.FiltroFecha);
            reclamos_table.repaint();
        }
        catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "Problema al conectar con la base de Datos: "
                    +e.getMessage(), "Error de Conexion", JOptionPane.ERROR_MESSAGE);
            this.dispose();
        }
    }//GEN-LAST:event_filtro_tiposActionPerformed

    private void filtro_tiempoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filtro_tiempoActionPerformed
        try {
            this.FiltroFecha = (String)(tiempo_reclamos.getSelectedItem());
            reclamos.FiltrarReclamos(this.FiltroTipo, this.FiltroFecha);
            reclamos_table.repaint();
        }
        catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "Problema al conectar con la base de Datos: "
                    +e.getMessage(), "Error de Conexion", JOptionPane.ERROR_MESSAGE);
            this.dispose();
        }
    }//GEN-LAST:event_filtro_tiempoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VerReclamos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VerReclamos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VerReclamos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VerReclamos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new VerReclamos().setVisible(true);
                }
                catch (Exception e) {}
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox filtro_tiempo;
    private javax.swing.JComboBox filtro_tipos;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable reclamos_table;
    // End of variables declaration//GEN-END:variables
}

 class ModeloReclamos extends AbstractTableModel {
        /*Variable con el titulo de las columnas*/
        private String[] columnNames = {"Autor del Reclamo",
                                        "Fecha de Modificacion",
                                        "Hora de Modificacion",
                                        "Tipo",
                                        "Asunto"
        };
        
        /* Variable donde cada elemento (String[]) es una fila distinta
         * Dentro del arreglo la informacion esta contenida en el mismo
         * orden en que van los titulos de las columnas*/
        private ArrayList<String []> data = new ArrayList<String[]>();
	    

        /* Constructor del Modelo de la lista de reclamos, 
         * empezamos obteniendo todos los reclamos*/
        public ModeloReclamos() throws SQLException {
            /* Obtenemos el Historial de ese equipo*/
            BDAdmin motor = new BDAdmin("SELECT * FROM RECLAMOS");
            ResultSet rs = motor.consulta();
            while (rs.next()) {
                 String[] fila = { rs.getString("autor"), 
                     rs.getString("fecha"), rs.getString("hora"), 
                     rs.getString("tipo"), 
                     rs.getString("asunto") };
                 data.add(fila);
            };           
        }
        
        /*Filtramos los reclamos ya sean bien por el tipo o por la fecha*/
        public void FiltrarReclamos(String filtro_tipo, String filtro_fecha) 
                throws SQLException {
            /* Inicializamos los las columnas y variables*/
            data = new ArrayList<String[]>();
            BDAdmin motor = new BDAdmin("SELECT * FROM RECLAMOS");
            ResultSet rs = motor.consulta();
            
            /*Si no se quieren mostrar todos los reclamos*/
            if (!(filtro_tipo.equals("Todo")) || !(filtro_fecha.equals("Todo"))) {
                /*Si no se filtra por fecha*/
                if (filtro_fecha.equals("Todo")) {
                    int num_tipo = 0;
                    if (filtro_tipo.equals("Remocion de Archivo")) 
                    { num_tipo = 1; }
                    
                    motor.setQuery("SELECT * FROM RECLAMOS WHERE tipo = "
                            + Integer.toString(num_tipo));
                    rs = motor.consulta();
                }
                /*Si no se filtra por tipo*/
                else if (filtro_tipo.equals("Todo")) {
                    /*Obtenemos la fecha actual*/
                    Date fecha_actual = new Date();
                    Calendar c = new GregorianCalendar();
                    c.setTime(fecha_actual);
        
                    String dia = Integer.toString(c.get(Calendar.DATE));
                    String mes = Integer.toString(c.get(Calendar.MONTH));
                    String annio = Integer.toString(c.get(Calendar.YEAR));
                                  
                    String fecha_buscar = dia + "/" + mes + "/" + annio;
                    motor.setQuery("SELECT * FROM RECLAMOS WHERE fecha = \'"
                            + fecha_buscar + "\'");
                    rs = motor.consulta();                         
                }
                /*Si se filtran por tipo y fecha*/
                else {
                    /*Convertimos al tipo de la base de datos*/
                    int num_tipo = 0;
                    if (filtro_tipo.equals("Remocion de Archivo")) 
                    { num_tipo = 1; }
                    
                    /*Obtenemos la fecha actual*/
                    Date fecha_actual = new Date();
                    Calendar c = new GregorianCalendar();
                    c.setTime(fecha_actual);
        
                    String dia = Integer.toString(c.get(Calendar.DATE));
                    String mes = Integer.toString(c.get(Calendar.MONTH));
                    String annio = Integer.toString(c.get(Calendar.YEAR));
                                
                    String fecha_buscar = dia + "/" + mes + "/" + annio;
                    motor.setQuery("SELECT * FROM RECLAMOS WHERE fecha = \'" + fecha_buscar 
                            + "\' AND tipo = " + Integer.toString(num_tipo));
                    rs = motor.consulta();                         
                }
            }
            /*Obtenemos los resultados de la consulta*/
            while (rs.next()) {
                 String[] fila = { rs.getString("autor"), 
                     rs.getString("fecha"), rs.getString("hora"), 
                     rs.getString("tipo"), 
                     rs.getString("asunto") };
                 data.add(fila);
            };
        }
        
        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.size();
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data.get(row)[col];
        }
        
 }